package com.cloudlead.common.lang.persistence;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/10/14.
 */
public class ObjectMap implements java.io.Serializable {
    public HashMap data;
    public ObjectMap(Object object, String columns){
                data = new HashMap();
            for (String fld:columns.split(",")) {
                fld = fld.trim();
                while (fld.indexOf("  ")>=0) fld=fld.replaceAll("  "," ");
                String fName=fld;
                if (fld.indexOf(" ")>0){
                    fName = fld.substring(fld.indexOf(" ")+1);
                    fld = fld.substring(0,fld.indexOf(" "));
                }
                if (fld.indexOf(".")>0){
                    String[] exFld= fld.split("\\.");
                    Object childObj=getFieldValue(object,exFld[0]);
                    data.put(fName,getFieldValue(childObj,exFld[1]));
                }else{
                    data.put(fName,getFieldValue(object,fld));
                }
            }
        }
    public Object getFieldValue(Object obj, String fldName){
        if (obj==null) return null;
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            for(Field f : fields) {
                f.setAccessible(true);
                if (f.getName().equalsIgnoreCase(fldName))
                    return f.get(obj);
            }
        } catch (IllegalAccessException e) {
            return null;
        }
        return null;
    }
    }
